//
//  ZZTalkListCell.m
//  Qzone
//
//  Created by zhangxy on 2018/7/20.
//  Copyright © 2018年 zhang. All rights reserved.
//

#import "ZZTalkListCell.h"

#import <SDWebImage/UIImageView+WebCache.h>
#import "ZZShareView.h"
#import <MWPhotoBrowser.h>

@implementation ZZTalkListCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    _imgAvatar.layer.cornerRadius = 22.0f;
    _imgAvatar.layer.masksToBounds = YES;
    
    [_labTitle setFont:FontFiftent];
    _labTitle.numberOfLines = 0;
    [_labTitle setTextColor:UIColorFromRGB(TextSizeOneColor)];
    
    
    [_labName setFont:FontFiftent];
    [_labName setTextColor:UIColorFromRGB(TextSizeOneColor)];
    
    [_btnAttent.titleLabel setFont:FontFiftent];
    _btnAttent.layer.cornerRadius = 3.0f;
    _btnAttent.layer.masksToBounds = YES;
    [_btnAttent setTitleColor:UIColorFromRGB(TextWhiteColor) forState:0];
    [_btnAttent setBackgroundColor:UIColorFromRGB(BgTitleColor)];
    [_btnAttent addTarget:self action:@selector(onCotrolClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [_btnAttent setTitle:@"关注" forState:0];
    
    [_labType setFont:FontThirteen];
    [_labType setTextColor:UIColorFromRGB(BgTitleColor)];
    
    [_labTime setFont:FontThirteen];
    [_labTime setTextColor:UIColorFromRGB(BgLineColor)];
    
    [self setBtnStype:_btnFav image:@"Combined_Shape"];
    [self setBtnStype:_btnComment image:@"btn_comment"];
    [self setBtnStype:_btnStar image:@"icon_fav"];
    [self setBtnStype:_btnShare image:@"icon_sharenew"];
    
    [_btnShare setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [_btnShare setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
    
    _viewContent.userInteractionEnabled = YES;
    self.userInteractionEnabled = YES;
    self.contentView.userInteractionEnabled = YES;
}

-(void)setBtnStype:(UIButton *) btn image:(NSString *)imgName{
    [btn setImage:[UIImage imageNamed:imgName] forState:0];
    [btn setTitleColor:UIColorFromRGB(TextSizeOneColor) forState:0];
    [btn.titleLabel setFont:ListElevenFont];
    [btn setTitle:@"" forState:0];
    [btn setTitleEdgeInsets:UIEdgeInsetsMake(0, 2, 0, 0)];
    [btn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [btn setBackgroundColor:UIColor.clearColor];
    [btn addTarget:self action:@selector(onCotrolClick:) forControlEvents:UIControlEventTouchUpInside];
    
    btn.userInteractionEnabled = YES;
}

-(void)onCotrolClick:(UIButton *)btn{
    ZZTopicCellClickType type = 0;
    if([btn isEqual:_btnShare]){
        type = ZZClickShare;
    }else if([btn isEqual:_btnFav]){
        type = ZZClickFav;
    }else if([btn isEqual:_btnStar]){
        type = ZZClickStar;
    }else if([btn isEqual:_btnComment]){
        type = ZZClickComment;
    }else if([btn isEqual:_btnAttent]){
        type = ZZClickAttentUser;
    }
    
    if(_delegate && [self.delegate respondsToSelector:@selector(onCellItemClick:obj:)]){
        [self.delegate onCellItemClick:type obj:self.tempModel];
    }
}


-(void) moreComment:(UITapGestureRecognizer *) tap{
    if(_delegate && [self.delegate respondsToSelector:@selector(onCellItemClick:obj:)]){
        [self.delegate onCellItemClick:ZZClickComment obj:self.tempModel];
    }
}


-(void)dataToView:(ForumEntity *) topic{
    self.tempModel = topic;
    self.backgroundColor = UIColor.clearColor;
    [self setUserViewData:topic];
    [_imgBgView setBackgroundColor:UIColor.whiteColor];
    _imgBgView.layer.cornerRadius = 10.0f;
    _imgBgView.layer.masksToBounds = YES;
    
    CGRect uf = _imgBgView.frame;
    uf.size.height = CGRectGetMaxY(_viewControl.frame) + 10;
    _imgBgView.frame = uf;
    
    if([topic.user_info.user_relation intValue] == 1){
        [self.btnAttent setTitle:@"取消" forState:0];
    }else{
        [self.btnAttent setTitle:@"关注" forState:0];
    }
    
    self.frame = CGRectMake(0, 0, ScreenWidth, CGRectGetMaxY(_imgBgView.frame)+10);
}

-(void)setUserViewData:(ForumEntity *) topic{
    [_imgAvatar sd_setImageWithURL:[NSURL URLWithString:convertToString(topic.user_info.user_avatar)] placeholderImage:[UIImage imageNamed:@"default_image"]];
    [_labName setText:topic.user_info.user_name];
    [_labTime setText:topic.last_user_time];

    
    [_labTitle setText:topic.title];
    
    CGSize st = [self autoWidthOfLabelHegith:_labTitle with:ScreenWidth - 40];
    
    
    if(topic.images.count == 0){
        CGRect contentF = _viewContent.frame;
        contentF.origin.y = CGRectGetMaxY(_labTitle.frame) + ((st.height>0)?10:0);
        contentF.size.height = 1;
        [_viewContent setFrame:contentF];
    }else{
        [self addContontImages:topic fy:CGRectGetMaxY(_labTitle.frame) + ((st.height>0)?10:0)];
    }
    
    
    
    CGRect typeF = _labType.frame;
    typeF.origin.y = CGRectGetMaxY(_viewContent.frame) + 10;
    _labType.frame = typeF;
    
    [_labType setText:@"没有"];
    
    [_btnFav setTitle:topic.count_fav forState:0];
    [_btnComment setTitle:convertIntToString((int)topic.count_post) forState:0];
    [_btnStar setTitle:topic.count_like forState:0];
    
    CGRect cf = _viewControl.frame;
    cf.origin.y = CGRectGetMaxY(_labType.frame);
    _viewControl.frame = cf;
}


-(void)addContontImages:(ForumEntity *)topic fy:(CGFloat ) y{
    [_viewContent.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    CGFloat maxWidth = ScreenWidth - 40;
    CGFloat space = 6;
    CGFloat minWidth = (ScreenWidth - 40 - space*2)/3;
    
    NSMutableArray *imgsObj = topic.images;
    if(imgsObj.count == 1){
        ImageEntity *firstObj = [imgsObj firstObject];
        UIImageView *imgView = [self createImageView];
        imgView.tag = 0;
        [imgView setFrame:CGRectMake(0, 0, maxWidth, maxWidth)];
        [imgView sd_setImageWithURL:[NSURL URLWithString:firstObj.image_url] placeholderImage:[UIImage imageNamed:@"default_image"]];
        
        imgView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        [tap addTarget:self action:@selector(imgTouchUpInside:)];
        [imgView addGestureRecognizer:tap];
        
        [_viewContent addSubview:imgView];
    }else{
        CGFloat x = 0;
        
        for (int i = 0;i<imgsObj.count; i ++ ) {
            if(i==6){
                break;
            }
            ImageEntity *firstObj = imgsObj[i];
            UIImageView *imgView = [self createImageView];
            [imgView sd_setImageWithURL:[NSURL URLWithString:firstObj.image_url] placeholderImage:[UIImage imageNamed:@"default_image"]];
            imgView.layer.cornerRadius = 3.0f;
            imgView.layer.masksToBounds = YES;
            imgView.tag = i;
            
            imgView.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
            [tap addTarget:self action:@selector(imgTouchUpInside:)];
            [imgView addGestureRecognizer:tap];
            
            // 张图片居中
            if(imgsObj.count == 2){
                x = (maxWidth - minWidth * 2 - space * 2)/2;
                
                if(i==0){
                    [imgView setFrame:CGRectMake(x, 0, minWidth, minWidth)];
                }else{
                    [imgView setFrame:CGRectMake(x + space, 0, minWidth, minWidth)];
                }
            }else if(imgsObj.count == 4){
                // 张图片，第一个放大，其它居中
                if(i==0){
                    [imgView setFrame:CGRectMake(x, 0, maxWidth, 216)];
                }else{
                    [imgView setFrame:CGRectMake(x, 222, minWidth, minWidth)];
                    x = minWidth + x + space;
                }
            }else{
                // 换行，3 、4、6情况
                if(i <= 2){
                    [imgView setFrame:CGRectMake(x, 0, minWidth, minWidth)];
                }else{
                    [imgView setFrame:CGRectMake(x, minWidth + 6, minWidth, minWidth)];
                }
                
                //换行
                if(i == 2){
                    x = 0;
                }else{
                    x = minWidth + x + space;
                }
            }
            [_viewContent addSubview:imgView];
            if(imgsObj.count > 6 && i == 5){
                UILabel *label =  [self createLabel];
                [label setFrame:imgView.frame];
                [label setTextAlignment:NSTextAlignmentCenter];
                [label setTextColor:UIColorFromRGB(TextWhiteColor)];
                [label setText:[NSString stringWithFormat:@"%zdP",imgsObj.count]];
                [_viewContent addSubview:label];
            }
        }
    }
    
    CGRect f = _viewContent.frame;
    f.origin.y = y;
    if(imgsObj.count == 1){
        f.size.height = maxWidth;
    }else if(imgsObj.count == 4){
        f.size.height = 216 + space + minWidth;
    }else{
        if(imgsObj.count <= 3){
            f.size.height = minWidth;
        }else{
            f.size.height = minWidth * 2 + space;
        }
    }
    [_viewContent setFrame:f];
}



-(UIImageView *)createImageView{
    UIImageView *imgView = [[UIImageView alloc] init];
    [imgView setContentMode:UIViewContentModeScaleAspectFill];
    imgView.clipsToBounds = YES;
    return imgView;
}

-(UILabel *) createLabel{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
    [label setTextAlignment:NSTextAlignmentLeft];
    [label setFont:FontThirteen];
    [label setTextColor:UIColorFromRGB(TextSizeOneColor)];
    [label setBackgroundColor:UIColor.clearColor];
    [label setNumberOfLines:0];
    return label;
}

/**
 计算Label高度
 
 @param label 要计算的label，设置了值
 @param width label的最大宽度
 */
- (CGSize )autoWidthOfLabel:(UILabel *)label with:(CGFloat )height{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(FLT_MAX, height);
    
    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
    
    //adjust the label the the new height.
    CGRect newFrame = label.frame;
    newFrame.size.width = expectedLabelSize.width;
    label.frame = newFrame;
    [label updateConstraintsIfNeeded];
    
    return expectedLabelSize;
}

- (CGSize )autoWidthOfLabelHegith:(UILabel *)label with:(CGFloat )width{
    //Calculate the expected size based on the font and linebreak mode of your label
    // FLT_MAX here simply means no constraint in height
    CGSize maximumLabelSize = CGSizeMake(width, FLT_MAX);
    
    CGSize expectedLabelSize = [label sizeThatFits:maximumLabelSize];
    
    //adjust the label the the new height.
    CGRect newFrame = label.frame;
    newFrame.size.height = expectedLabelSize.height;
    label.frame = newFrame;
    [label updateConstraintsIfNeeded];
    
    return expectedLabelSize;
}



/**
 *  点击查看大图
 *
 *  @param
 */
-(void) imgTouchUpInside:(UITapGestureRecognizer *)recognizer{
    DLog(@"我怎么不处罚呢：");
    UIImageView *_picView = (UIImageView*)recognizer.view;
    NSMutableArray *photos = [NSMutableArray new];
    for (int i = 0;i<self.tempModel.images.count; i ++ ) {
        ImageEntity *firstObj = self.tempModel.images[i];
        
        MWPhoto *photo = [MWPhoto photoWithURL:[NSURL URLWithString:firstObj.origin_image]];
        
        [photos addObject:photo];
    }
    
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithPhotos:photos];
    [browser setCurrentPhotoIndex:_picView.tag];
    browser.zoomPhotosToFill = YES;
    browser.displayNavArrows = YES;
    if(_delegate && [self.delegate respondsToSelector:@selector(onCellItemClick:obj:)]){
        [self.delegate onCellItemClick:ZZClickOpenVC obj:browser];
    }
    //
    //    CALayer *calayer = _picView.layer.mask;
    //    [_picView.layer.mask removeFromSuperlayer];
    //
    //
    //    NSMutableArray *photos = [[NSMutableArray alloc] init];
    //
    //    XHImageViewer *xh = [[XHImageViewer alloc] initWithImageViewerWillDismissWithSelectedViewBlock:^(XHImageViewer *imageViewer, UIImageView *selectedView) {
    //
    //    } didDismissWithSelectedViewBlock:^(XHImageViewer *imageViewer, UIImageView *selectedView) {
    //
    //        selectedView.layer.mask = calayer;
    //        [selectedView setNeedsDisplay];
    //
    //
    //        [photos removeAllObjects];
    //    } didChangeToImageViewBlock:^(XHImageViewer *imageViewer, UIImageView *selectedView) {
    //
    //    }];
    //
    ////    for (int i = 0;i<self.tempModel.images.count; i ++ ) {
    //////        if(i==_picView.tag){
    //////            [photos addObject:_picView];
    //////        }else{
    ////            ImageEntity *firstObj = self.tempModel.images[i];
    ////            UIImageView *imgView = [self createImageView];
    ////            imgView.tag = i;
    ////            [imgView setFrame:_picView.frame];
    ////            [imgView sd_setImageWithURL:[NSURL URLWithString:firstObj.image_url] placeholderImage:[UIImage imageNamed:@"default_image"]];
    ////            [photos addObject:imgView];
    //////        }
    ////
    ////    }
    //    [photos addObjectsFromArray:_viewContent.subviews];
    //
    //    //    xh.delegate = self;
    //    xh.disableTouchDismiss = NO;
    //    [xh showWithImageViews:photos selectedView:_picView];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
